﻿package com.bizmlib.ui.composite
{
	import flash.display.InteractiveObject;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	
	public class UICompositionItemDraggable extends UICompositionItem
	{
		protected var dragClickArea:InteractiveObject;
		
		
		override protected function afterRemovedFromStage():void
		{
			super.afterRemovedFromStage();
			
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, pressedMouseMove);
		}
		
		
		override protected function afterInit():void
		{
			//trace(this + ".afterInit(" + arguments + ")");
			
			super.afterInit();
			
			addEventListener(Event.ADDED_TO_STAGE, dragAddedToStage, false, 0, true);
		}
		protected function dragAddedToStage(event:Event):void
		{
			//trace(this + ".dragAddedToStage(" + arguments + ")");
			
			removeEventListener(Event.ADDED_TO_STAGE, dragAddedToStage);
			addEventListener(Event.REMOVED_FROM_STAGE, dragRemovedFromStage);
			
			(dragClickArea || stage).addEventListener(MouseEvent.MOUSE_DOWN, dragPressEventHandling);
		}
		protected function dragRemovedFromStage(event:Event):void
		{
			//trace(this + ".dragRemovedFromStage(" + arguments + ")");
			
			removeEventListener(Event.REMOVED_FROM_STAGE, dragRemovedFromStage);
			
			(dragClickArea || stage).removeEventListener(MouseEvent.MOUSE_DOWN, dragPressEventHandling);
			(dragClickArea || stage).removeEventListener(MouseEvent.MOUSE_UP, dragReleaseEventHandling);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, pressedMouseMove);
		}
		protected function dragPressEventHandling(event:MouseEvent):void
		{
			//trace(this + ".dragPressEventHandling(" + arguments + ")");
			
			if(!(dragClickArea || area))
			{
				return;
			}
			else if(!(dragClickArea || area).hitTestPoint(event.stageX, event.stageY))
			{
				return;
			}
			
			(dragClickArea || stage).addEventListener(MouseEvent.MOUSE_UP, dragReleaseEventHandling);
			stage.addEventListener(MouseEvent.MOUSE_MOVE, pressedMouseMove);
		}
		protected function dragReleaseEventHandling(event:MouseEvent):void
		{
			//trace(this + ".dragReleaseEventHandling(" + arguments + ")");
			
			(dragClickArea || stage).removeEventListener(MouseEvent.MOUSE_UP, dragReleaseEventHandling);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, pressedMouseMove);
		}
		private function pressedMouseMove(event:MouseEvent):void
		{
			(dragClickArea || stage).removeEventListener(MouseEvent.MOUSE_UP, dragReleaseEventHandling);
			stage.removeEventListener(MouseEvent.MOUSE_MOVE, pressedMouseMove);
			
			dispatchUICompositionItemEvent(UICompositionItemEvent.DRAG_INVOKED);
		}
	}
}